/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package report_qc_template;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.util.Date;
import javax.swing.JOptionPane;

/**
 *
 * @author dlao
 */
public class Report_QC_Template {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        EventQueue.invokeLater(new Runnable() {

            public void run() {
                ReportQCTemplateFrame frame = new ReportQCTemplateFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

class ReportQCTemplateFrame extends JFrame {

    public static final int DEFAULT_WIDTH = 390;
    public static final int DEFAULT_HEIGHT = 510;

    public ReportQCTemplateFrame() {
        setTitle("Report QC Template v3 by Diwen");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        setResizable(false);
        ReporctQCTemplateComponent component = new ReporctQCTemplateComponent();
        add(component);
    }
}

class ReporctQCTemplateComponent extends JPanel {

    private JPanel panel;
    private ActionListener addMetrics = new AddMetricsAction();
    private ActionListener generate = new GenerateAction();
    private ActionListener addScriptNum = new AddScriptNumAction();
    private ActionListener addReport = new AddReportAction();
    private ActionListener addNew = new AddNewAction();
    private ActionListener deleteMetrics = new DeleteMetricsAction();
    private ActionListener addStraightMove = new AddStraightMoveAction();
    private ActionListener deleteStraightMove = new DeleteStraightMoveAction();
    private ActionListener TestCase = new TestCaseAction();
    private ArrayList<String> metrics;
    private ArrayList<String> column;
    private JTextArea log;
    private JTextField text;
    private JFileChooser fc;
    private File output;
    private FileWriter fstream;
    private BufferedWriter out;
    private String day;
    private ArrayList<String> stepDesc;
    private ArrayList<String> stepExpectedResults;
    private ArrayList<String> straightMove;
    //   private ArrayList<String> descList;
    private String scriptNum;
    private String reportName;
    private int cycle;
    private int step;
    private JButton button;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;
    private JButton button6;
    private JButton button7;
    private JButton button8;
    private JButton button9;
    private Calendar cal;
    private SimpleDateFormat dateFormatLocal;
    private String newline;
    private int countStraightMove;
//    private int editCount;
//    private int metricsCount;
    private String testCase;
    private int z = 0;
    private int y = 0;
    private int q = 0;
    private String testName;

    public ReporctQCTemplateComponent() {
        newline = "\n" + "\n";
        cycle = 0;
        step = 0;
        countStraightMove = 0;
//        editCount = 0;
//        metricsCount = 0;
        dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
        metrics = new ArrayList<String>();
        column = new ArrayList<String>();
        stepDesc = new ArrayList<String>();
        stepExpectedResults = new ArrayList<String>();
        straightMove = new ArrayList<String>();
//        descList = new ArrayList<String>();
        panel = new JPanel();
        panel.setLayout(new GridLayout(5, 2));
        text = new JTextField(32);
        add(text, BorderLayout.NORTH);


        button = new JButton("Add/Change Report Name");
        button.setEnabled(true);
        button.addActionListener(addReport);
        panel.add(button);

        button7 = new JButton("Straight Move");
        button7.setEnabled(false);
        button7.addActionListener(addStraightMove);
        panel.add(button7);

        button2 = new JButton("Add Metrics");
        button2.setEnabled(false);
        button2.addActionListener(addMetrics);
        panel.add(button2);

        button3 = new JButton("add/Change Script Number");
        button3.setEnabled(false);
        button3.addActionListener(addScriptNum);
        panel.add(button3);

        button4 = new JButton("Generate Template");
        button4.setEnabled(false);
        button4.addActionListener(generate);
        panel.add(button4);


        button5 = new JButton("New");
        button5.setEnabled(false);
        button5.addActionListener(addNew);
        panel.add(button5);


        button6 = new JButton("Delete Metric");
        button6.setEnabled(false);
        button6.addActionListener(deleteMetrics);
        panel.add(button6);

        button8 = new JButton("Delete Straigh Move");
        button8.setEnabled(false);
        button8.addActionListener(deleteStraightMove);
        panel.add(button8);

        button9 = new JButton("Test Case");
        button9.setEnabled(true);
        button9.addActionListener(TestCase);
        panel.add(button9);


        log = new JTextArea(19, 33);
        log.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(log);
        add(panel, BorderLayout.CENTER);
        add(logScrollPane, BorderLayout.SOUTH);
    }

    private class TestCaseAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            String str = JOptionPane.showInputDialog(null, "Test Case(Rxxx): ", "Test Case", 1);

            if (str != null) {
                if (str.length() > 0) {
                    //descList.add(str);
                    testCase = str;
                    cal = Calendar.getInstance();
                    log.append("Test Case: " + str + "has added    " + dateFormatLocal.format(cal.getTime()) + newline);
                     button4.setEnabled(true);
                } else {
                    JOptionPane.showMessageDialog(null, "Please enter content.", "Test Case", 1);
                }
            }
        }
    }

    private class AddMetricsAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            if (text.getText().equals("")) {
                cal = Calendar.getInstance();
                log.append("Please Enter Metrics     " + dateFormatLocal.format(cal.getTime()) + newline);
            } else {
                cal = Calendar.getInstance();
                metrics.add(text.getText());
                //log.setText("");
                log.append("Metric: " + text.getText() + " has added     " + dateFormatLocal.format(cal.getTime()) + newline);
                text.setText("");
                button6.setEnabled(true);
            }
        }
    }

    private class AddStraightMoveAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            if (text.getText().equals("")) {
                cal = Calendar.getInstance();
                log.append("Please Enter Straight Move     " + dateFormatLocal.format(cal.getTime()) + newline);
            } else {
                cal = Calendar.getInstance();
                straightMove.add(text.getText());
                countStraightMove++;
                //log.setText("");
                log.append("Straight Move: " + text.getText() + " has added     " + dateFormatLocal.format(cal.getTime()) + newline);
                text.setText("");
                button8.setEnabled(true);
            }
        }
    }

    public boolean isNumeric(String str) {
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

    private class DeleteStraightMoveAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            if (straightMove.isEmpty()) {
                cal = Calendar.getInstance();
                log.setText("No Straight Move!      " + dateFormatLocal.format(cal.getTime()) + newline);
                button8.setEnabled(false);
            } else {
                int num5 = 0;
                String str5 = "";
                Iterator itr = straightMove.iterator();

                while (itr.hasNext()) {
                    num5++;
                    str5 = str5 + num5 + ". " + itr.next() + "\n";
                }

                String str = JOptionPane.showInputDialog(null, str5 + "Choose the number you want to delete : ",
                        "Delete Straight Move", 1);

                if (str != null) {
                    if (str.length() > 0) {
                        if (isNumeric(str) == true) {
                            int n = JOptionPane.showConfirmDialog(
                                    null,
                                    "Are you sure to delete : " + straightMove.get(Integer.parseInt(str) - 1),
                                    "Delete Straight Move",
                                    JOptionPane.YES_NO_OPTION);
                            if (n == 0) {
                                log.append("Deleted Straight Move: " + straightMove.get(Integer.parseInt(str) - 1) + "      " + dateFormatLocal.format(cal.getTime()) + newline);
                                straightMove.remove(Integer.parseInt(str) - 1);
                                countStraightMove--;
                            }
                            if (straightMove.isEmpty()) {
                                button8.setEnabled(false);
                                if (metrics.isEmpty()) {
                                    button4.setEnabled(false);
                                }
                            }
                        } else {
                            JOptionPane.showMessageDialog(null, "Please enter number.", "Delete Straight Move", 1);
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "Please enter number.", "Delete Straight Move", 1);
                    }
                }
            }
        }
    }

    private class AddScriptNumAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            if (text.getText().equals("")) {
                cal = Calendar.getInstance();
                log.append("Please Enter Script Number     " + dateFormatLocal.format(cal.getTime()) + newline);
            } else {
                //log.setText("");
                cal = Calendar.getInstance();
                scriptNum = text.getText();
                log.append("Script number: " + scriptNum + " has added     " + dateFormatLocal.format(cal.getTime()) + newline);
                text.setText("");
               
            }
        }
    }

    private class AddReportAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            if (text.getText().equals("")) {
                cal = Calendar.getInstance();
                log.append("Please Enter Report Name     " + dateFormatLocal.format(cal.getTime()) + newline);
            } else {
                cal = Calendar.getInstance();
                reportName = text.getText();
                log.append("Report: " + reportName + " has added      " + dateFormatLocal.format(cal.getTime()) + newline);
                text.setText("");
                //   button.setEnabled(false);
                button2.setEnabled(true);
                button3.setEnabled(true);
                button7.setEnabled(true);
            }
        }
    }

    private class AddNewAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            button.setEnabled(true);
            button2.setEnabled(false);
            button3.setEnabled(false);
            button4.setEnabled(false);
            button5.setEnabled(false);
        }
    }

    private class DeleteMetricsAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            if (metrics.isEmpty()) {
                cal = Calendar.getInstance();
                log.setText("No metric!      " + dateFormatLocal.format(cal.getTime()) + newline);
                button6.setEnabled(false);
            } else {
                int num5 = 0;
                String str5 = "";
                Iterator itr = metrics.iterator();

                while (itr.hasNext()) {
                    num5++;
                    str5 = str5 + num5 + ". " + itr.next() + "\n";
                }
                String str = JOptionPane.showInputDialog(null, str5 + "Choose the number you want to delete : ",
                        "Delete Metric", 1);

                if (str != null) {
                    if (str.length() > 0) {
                        if (isNumeric(str) == true) {
                            int n = JOptionPane.showConfirmDialog(
                                    null,
                                    "Are you sure to delete : " + metrics.get(Integer.parseInt(str) - 1),
                                    "Delete Straight Move",
                                    JOptionPane.YES_NO_OPTION);
                            if (n == 0) {
                                log.append("Deleted Straight Move: " + metrics.get(Integer.parseInt(str) - 1) + "      " + dateFormatLocal.format(cal.getTime()) + newline);
                                metrics.remove(Integer.parseInt(str) - 1);
                                countStraightMove--;
                            }
                            if (metrics.isEmpty()) {
                                button6.setEnabled(false);
                                if (straightMove.isEmpty()) {
                                    button4.setEnabled(false);
                                }
                            }
                        } else {
                            JOptionPane.showMessageDialog(null, "Please enter number.", "Delete Straight Move", 1);
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "Please enter number.", "Delete Straight Move", 1);
                    }
                }
            }
        }
    }

    private class GenerateAction implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            fc = new JFileChooser();
            int returnVal = fc.showSaveDialog(ReporctQCTemplateComponent.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                output = fc.getSelectedFile();
                GenerateTemplate();
            }
        }
    }

    private String printMetric(ArrayList<String> list) {
        String str = "";
        int num = 0;
        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            num++;
            str = str + num + ". " + itr.next() + "; ";
        }
        return str;
    }

    private void GenerateTemplate() {
        String str2, str3, str4;
        int num2 = 0;
        int num3 = 0;
        try {
//            int stepCount = straightMove.size() + metrics.size() * descList.size() + 3;
            int stepCount = straightMove.size() + metrics.size() + 3;
            fstream = new FileWriter(output, true);
            out = new BufferedWriter(fstream);

            for (int c = 0; c < 3; c++) {

                q = 0;
                step = 0;
                cycle = c + 1;
                stepDesc.add("Execute " + reportName + " test SQL Script (Script " + scriptNum + " ) output  (in Excel)  and identify cycle "
                        + cycle + " records. ");
                stepDesc.add("Login to MS Reports folder via web browser. Select " + reportName);
                stepDesc.add("In the Date prompts: enter Cycle "
                        + cycle + " date in both From and To date fields. Keep all the other default prompts. And execute the report.");

                stepExpectedResults.add("A list of metrics and values from " + scriptNum + " cycle " + cycle + " SQL script are generated.");
                stepExpectedResults.add("Login Successfully.");
                stepExpectedResults.add("Report accept both date entries.");
                if (cycle == 1) {
                    day = "Single Day";
                } else if (cycle == 2) {
                    day = "Multi Day";
                } else {
                    day = "Cross Month";
                }
                // System.out.println("Cycle: " + cycle);
                for (int v = 0; v < 2; v++) {
                    q = v + 1;

                    z = 0;
                    y = 0;
                    if(cycle ==1 && q == 1){
                        testName = "SingleDayDefaultValues";
                    }else if(cycle ==1 && q == 2){
                        testName = "SingleDayOneParater";
                    }else if(cycle ==2 && q == 1){
                        testName = "MultiDayPageAll";
                    }else if(cycle ==2 && q == 2){
                        testName = "MultisSingleDayPageBy";
                    }else if(cycle ==3 && q == 1){
                        testName = "AMonthPageAll";
                    }else if(cycle ==3 && q == 2){
                        testName = "AMonthSinglePageBy";
                    }
                    for (int x = 0; x < stepCount; x++) {

                        step = x + 1;
                        column.add("Reporting\\R - Usage\\" + reportName);//a
                        column.add(testCase + "00" + cycle + " - 0" + q);//b
                        column.add(testName);//c
                        column.add("Verification of the following: 1.Metric data is correct for Cycle "
                                + cycle + " data " + "( " + day + " )" + ". "
                                + "The Test script for this test cases is " + scriptNum + " cycle " + cycle + "; 2. The totals match the detail. "
                                + "The metrics in the Report are: " + printMetric(metrics)); // d
                        column.add("P2-High"); //e
                        column.add("Step " + step);// f

                        if (step < 4) {
                            column.add(stepDesc.get(x));// g
                            column.add(stepExpectedResults.get(x)); //g  h
                        } else {
                            if (countStraightMove > 0) {
                                column.add("Compare " + straightMove.get(z) + " in the report with Step 1's SQL result for " + straightMove.get(z)
                                        + ". These two numbers is matching");//g
                                column.add(straightMove.get(z) + " from report matches SQL results"); //h
                                countStraightMove--;
                                z++;
                            } else if (metrics.isEmpty() == false) {
                                column.add("Compare the Total of " + metrics.get(y) + " in the report with Step 1's SQL result for " + metrics.get(y)
                                        + ". These two numbers is matching");//g
                                column.add(metrics.get(y) + " from report matches SQL results"); //h
                                y++;
                            }
                        }
                        out.append(arrayToString(column) + "\n");
                        column.clear();
                    }
                    countStraightMove = straightMove.size();
                }
                stepExpectedResults.clear();
                stepDesc.clear();
            }
            out.close();
            // descList.clear();
            text.setText("");
            log.setText("");
            cal = Calendar.getInstance();
            log.append("Summary" + newline);
            log.append("Report Name: " + reportName + newline);
            log.append("Scripts Number: " + scriptNum + newline);
             log.append("Test Case: " + testCase + newline);
            if (straightMove.isEmpty() == false) {
                Iterator itr2 = straightMove.iterator();
                log.append("Total Straight Move:" + "\n");
                while (itr2.hasNext()) {
                    num3++;
                    str3 = itr2.next() + "\n";
                    log.append(num3 + ". " + str3);
                }
                log.append("\n");
            }

            if (metrics.isEmpty() == false) {
                Iterator itr = metrics.iterator();
                log.append("Total Metrics:" + "\n");
                while (itr.hasNext()) {
                    num2++;
                    str2 = itr.next() + "\n";
                    log.append(num2 + ". " + str2);
                }
                log.append("\n");
            }

            str4 = output.getPath();
            log.append("Save to file: " + str4 + "    " + dateFormatLocal.format(cal.getTime()) + newline);
            metrics.clear();
            straightMove.clear();
            countStraightMove = 0;
            button.setEnabled(false);
            button2.setEnabled(false);
            button3.setEnabled(false);
            button4.setEnabled(false);
            button5.setEnabled(true);
            button6.setEnabled(false);
            button7.setEnabled(false);
            button8.setEnabled(false);
        } catch (IOException ex) {
            log.setText("");
            cal = Calendar.getInstance();
            log.setText("Error! Please close the opened Excel file    " + dateFormatLocal.format(cal.getTime()) + newline);
        }
    }

    private ArrayList<String> Itr(ArrayList<String> a) {
        return a;
    }

    private String arrayToString(ArrayList<String> a) {
        String str = "";
        Iterator itr = a.iterator();
        while (itr.hasNext()) {
            str = str + itr.next() + ",";
        }
        //  System.out.print(str);
        return str;
    }
}
